# -*- coding:utf-8 -*-

from django.http import HttpResponse,HttpResponseRedirect,HttpResponseForbidden
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.shortcuts import redirect,render, get_object_or_404
from django.contrib import auth, messages
from django.contrib.auth.models import User, Group
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.db.models import Count, Q
from .models import Book, Category
from disn.utilities import *
import random, requests, json, os, base64, re


# from weixin.models import *


@csrf_exempt
def book_youhui(request):
    print('func book_youhui reload()')
    wechat_from = request.GET.get('from', None)
    if wechat_from: #https://segmentfault.com/q/1010000002566983/a-1020000002567095
        return redirect('/book/youhui/')
    s = request.GET.get('s', None)
    page = int(request.GET.get('page', 1))
    if s:
        print('Search Keyword: %s' %s)
        source = request.GET.get('source', None)
        date_before_60_days = get_date_by_delta(datetime.datetime.today(), - 60)
        items = Item.objects.filter(create_at__gte=date_before_60_days, top_category__pinyin='tu-shu-yin-xiang', active=True, article_title__icontains=s).order_by('-create_at')
    else:
        date_before_30_days = get_date_by_delta(datetime.datetime.today(), - 30)
        items = Item.objects.filter(create_at__gte=date_before_30_days, top_category__pinyin='tu-shu-yin-xiang', active=True).order_by('-create_at')
    items = items[:1800]
    p = Paginator(items, 60)
    page_range = p.page_range
    current_page_items = p.page(page)
    is_ajax_req = request.GET.get('isAjax', None)
    if is_ajax_req:
        response_data = {}
        results = [ob.as_json() for ob in current_page_items]
        response_data['result'] = results
        response_data['page'] = page
        return HttpResponse(json.dumps(response_data), content_type="application/json")
    ua = request.META['HTTP_USER_AGENT'].lower()
    if request.user_agent.is_mobile or ua.find('micromessenger') >= 0:
        category = 'tu-shu-yin-xiang'
        return render(request, 'book/youhui.html', {'category':category, 'category_name':Category.get_name_by_pinyin(category) ,'page':page, 'page_range':page_range, 'current_page_items': current_page_items})
    else:
        return render(request, 'pc/youhui.html', {'page':page, 'page_range':page_range, 'current_page_items': current_page_items})

def book_detail(request, id):
    print('func book_detail reload()')
    # display_request_meta(request)
    # referrer = request.user.profile.id if request.user else '0'
    referrer = '0'
    wechat_from = request.GET.get('from', None)
    if wechat_from: #https://segmentfault.com/q/1010000002566983/a-1020000002567095
        return redirect('/book/youhui/%s/' %id)
    is_redirect = request.GET.get('redirect', None)
    item = get_object_or_404(Item, Q(pk=id) | Q(article_id=id))
    # return render(request, 'm/detail.html', {'item': item, 'jssdk_signature':get_jssdk_signature(request)})
    ua = request.META['HTTP_USER_AGENT'].lower()
    promotion_url = None
    if ua.find('micromessenger') >= 0: # user from wechat
        if is_redirect:
            if item.commodity_url_refer_mb:
                promotion_url = item.commodity_url_refer_mb
            elif item.commodity_url_refer:
                promotion_url = item.commodity_url_refer
            else:
                promotion_url = item.commodity_url
            return redirect(promotion_url)
        else:
            return render(request, 'book/detail.html', {'referrer':referrer, 'item': item})
    else:
        if is_redirect:
            if item.commodity_url_refer:
                promotion_url = item.commodity_url_refer
            else:
                promotion_url = item.commodity_url
            return redirect(promotion_url)
        else:
            return render(request, 'zdm/detail.html', {'referrer':referrer, 'category':item.top_category.pinyin, 'item': item})
